ReactJS Ultra For Beginners
🔄 React Query (TanStack Query)
What is React Query?
- A powerful data synchronization library for React
- Handles server state management (caching, background updates, error handling)
- Provides hooks for fetching, caching, and updating data
- Reduces boilerplate for data fetching
📝 Basic Setup
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query"; // Create a client const queryClient = new QueryClient(); // Wrap your app function App() { return ( <QueryClientProvider client={queryClient}> <UserList /> </QueryClientProvider> ); } // Use in component function UserList() { const { data: users, isLoading, error, } = useQuery({ queryKey: ["users"], queryFn: () => fetch("/api/users").then((res) => res.json()), }); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return ( <ul> {users?.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> ); }
🔑 Core Hooks
1. useQuery - For fetching data:
function UserProfile({ userId }) { const { data: user, isLoading, error, refetch, } = useQuery({ queryKey: ["user", userId], queryFn: () => fetchUser(userId), enabled: !!userId, // Only run if userId exists staleTime: 5 * 60 * 1000, // 5 minutes cacheTime: 10 * 60 * 1000, // 10 minutes }); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return ( <div> <h1>{user.name}</h1> <p>{user.email}</p> <button onClick={() => refetch()}>Refresh</button> </div> ); }
2. useMutation - For updating data:
function CreateUser() { const mutation = useMutation({ mutationFn: (newUser) => createUser(newUser), onSuccess: (data) => { // Invalidate and refetch users queryClient.invalidateQueries({ queryKey: ["users"] }); }, onError: (error) => { console.error("Error creating user:", error); }, }); const handleSubmit = (userData) => { mutation.mutate(userData); }; return ( <form onSubmit={handleSubmit}> <button type="submit" disabled={mutation.isPending}> {mutation.isPending ? "Creating..." : "Create User"} </button> </form> ); }
🎯 Common Patterns
Data Fetching with Parameters:
function PostList({ category }) { const { data: posts, isLoading } = useQuery({ queryKey: ["posts", category], queryFn: () => fetchPosts(category), enabled: !!category, }); if (isLoading) return <div>Loading posts...</div>; return ( <div> {posts?.map((post) => ( <Post key={post.id} post={post} /> ))} </div> ); }
Optimistic Updates:
function TodoList() { const queryClient = useQueryClient(); const updateTodoMutation = useMutation({ mutationFn: updateTodo, onMutate: async (newTodo) => { // Cancel outgoing refetches await queryClient.cancelQueries({ queryKey: ["todos"] }); // Snapshot previous value const previousTodos = queryClient.getQueryData(["todos"]); // Optimistically update queryClient.setQueryData(["todos"], (old) => old.map((todo) => todo.id === newTodo.id ? { ...todo, ...newTodo } : todo ) ); return { previousTodos }; }, onError: (err, newTodo, context) => { // Rollback on error queryClient.setQueryData(["todos"], context.previousTodos); }, onSettled: () => { // Always refetch after error or success queryClient.invalidateQueries({ queryKey: ["todos"] }); }, }); return ( <div> {todos?.map((todo) => ( <TodoItem key={todo.id} todo={todo} onUpdate={(updates) => updateTodoMutation.mutate(updates)} /> ))} </div> ); }
Infinite Queries:
function InfinitePostList() { const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading } = useInfiniteQuery({ queryKey: ["posts"], queryFn: ({ pageParam = 1 }) => fetchPosts(pageParam), getNextPageParam: (lastPage, pages) => { return lastPage.hasMore ? pages.length + 1 : undefined; }, }); if (isLoading) return <div>Loading...</div>; return ( <div> {data.pages.map((page, i) => ( <div key={i}> {page.posts.map((post) => ( <Post key={post.id} post={post} /> ))} </div> ))} <button onClick={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage} > {isFetchingNextPage ? "Loading more..." : hasNextPage ? "Load More" : "Nothing more to load"} </button> </div> ); }
🔧 Advanced Features
Query Invalidation:
const queryClient = useQueryClient(); // Invalidate specific queries queryClient.invalidateQueries({ queryKey: ["users"] }); // Invalidate queries with pattern queryClient.invalidateQueries({ queryKey: ["users"], exact: false }); // Invalidate all queries queryClient.invalidateQueries();
Prefetching:
function UserList() { const queryClient = useQueryClient(); const prefetchUser = (userId) => { queryClient.prefetchQuery({ queryKey: ["user", userId], queryFn: () => fetchUser(userId), }); }; return ( <div> {users?.map((user) => ( <div key={user.id} onMouseEnter={() => prefetchUser(user.id)}> {user.name} </div> ))} </div> ); }
Background Refetching:
function RealTimeData() { const { data, isLoading } = useQuery({ queryKey: ["real-time-data"], queryFn: fetchRealTimeData, refetchInterval: 5000, // Refetch every 5 seconds refetchIntervalInBackground: true, // Continue refetching when tab is not active }); return <div>{/* Your component */}</div>; }
🎯 Error Handling
function UserProfile({ userId }) { const { data: user, error, isError, } = useQuery({ queryKey: ["user", userId], queryFn: () => fetchUser(userId), retry: 3, // Retry 3 times on failure retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000), }); if (isError) { return ( <div> <h2>Error loading user</h2> <p>{error.message}</p> <button onClick={() => refetch()}>Try again</button> </div> ); } return <div>{/* User profile */}</div>; }
🔄 Mutations with Optimistic Updates
function TodoItem({ todo }) { const queryClient = useQueryClient(); const toggleMutation = useMutation({ mutationFn: (todoId) => toggleTodo(todoId), onMutate: async (todoId) => { await queryClient.cancelQueries({ queryKey: ["todos"] }); const previousTodos = queryClient.getQueryData(["todos"]); queryClient.setQueryData(["todos"], (old) => old.map((todo) => todo.id === todoId ? { ...todo, completed: !todo.completed } : todo ) ); return { previousTodos }; }, onError: (err, todoId, context) => { queryClient.setQueryData(["todos"], context.previousTodos); }, onSettled: () => { queryClient.invalidateQueries({ queryKey: ["todos"] }); }, }); return ( <div> <input type="checkbox" checked={todo.completed} onChange={() => toggleMutation.mutate(todo.id)} /> <span>{todo.text}</span> </div> ); }
⚠️ Best Practices
- Use descriptive query keys - make them unique and meaningful
- Handle loading and error states - always provide user feedback
- Use staleTime and cacheTime - optimize for your use case
- Invalidate queries after mutations - keep data in sync
- Use optimistic updates - improve perceived performance
- Prefetch data - improve user experience
- Handle errors gracefully - provide retry mechanisms
111 / 111 videos100% complete
Course Completed!
Great job! You've finished all videos.
Welcome to the Course
Intro to The Course
3:33How to Learn This Course
3:02What is React and Why You Should Learn It?
4:14Getting Started with React
Installing Nodejs
3:03Setting up a React Development Environment
4:30VSCode Extensions
3:17JavaScript Refresher - All JS You Need To Know Before React
Functions
5:39Ternary and Logical Operators
7:21Objects and Arrays
7:11Map and Filter Functions
7:15Array Function Key Prop
3:13String Templating
4:27Basic React Concepts
React Project Folder Structure
6:55An Intro To JSX
10:33What is the App Component?
2:46How to use Components?
10:23Lists in React
9:45CSS in React
9:10Component Project - Build A Simple Website
First React Project
3:34Making A Navbar
7:11Displaying Images
7:11Making the About Us Section
2:35Creating A Footer
3:38Intro To States In React
What is the useState Hook?
10:38What is the useState Hook? Part 2
4:42What is the useState Hook? Part 3
14:50Intro React Project - Task Tracker App
Beginner Project - Task Tracker App
35:03React Component Lifecycle
The Virtual Dom
1:50React Component Lifecycle
1:42The useEffect Hook
15:40The useEffect Hook Part 2
8:41Routing in React
React Router
14:05React Router Part 2
14:28Advanced Forms In React
Forms in React - React Hook Form
25:36State Management
Intro To State Management - Global States
18:37Beginner Project - Build A Blog App
Intermediate Project - Build A Blog App
40:40Intermediate Project - Build A Blog App Part 2
26:57Other Useful React Hooks
Rules of Hooks
4:05Learn the useReducer Hook
9:54Learn the useRef Hook
12:03Making Your Own Custom Hook
12:10Advanced State Management - Zustand
Why Zustand?
5:22Intro to Zustand
11:08Zustand Subscriptions
9:01Advanced Data Handling With React Query
Why React Query?
6:18The useQuery Hook
16:38The useMutation Hook
8:45